package com.ruoyi.service.impl;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.domain.vo.CartGoodsDTO;
import com.ruoyi.domain.vo.GoodsEvaluateVo;
import com.ruoyi.domain.vo.GoodsVo;
import com.ruoyi.mapper.CartGoodsDTOMapper;
import com.ruoyi.mapper.ExchangeMallMapper;
import com.ruoyi.mapper.GoodsEvaluateVoMapper;
import com.ruoyi.service.IExchangeMallService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.GoodsSystemVo;
import com.ruoyi.system.mapper.GoodsEvaluateMapper;
import com.ruoyi.system.mapper.OrderItemMapper;
import com.ruoyi.system.service.ICartService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.impl.GoodsServiceImpl;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import com.ruoyi.system.service.impl.SysDictDataServiceImpl;
import com.ruoyi.system.service.impl.UserInfoServiceImpl;
import com.ruoyi.utils.TanpuhuiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.time.LocalDate.now;

@Service
public class ExchangeMallServiceImpl implements IExchangeMallService {

    @Autowired
    private TanpuhuiUtils tanpuhuiUtils;

    @Autowired
    private UserInfoServiceImpl userInfoService;

    @Autowired
    private SysConfigServiceImpl sysConfigService;

    @Autowired
    private GoodsServiceImpl goodsService;

    @Autowired
    private GoodsEvaluateVoMapper goodsEvaluateVoMapper;

    @Autowired
    private ExchangeMallMapper exchangeMallMapper;

    @Autowired
    private GoodsEvaluateMapper goodsEvaluateMapper;

    @Autowired
    private SysDictDataServiceImpl sysDictDataService;

    @Autowired
    private CartGoodsDTOMapper cartGoodsDTOMapper;

    @Autowired
    private ICartService cartService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    public List<GoodsSystemVo> getGoodsList(Long goodsTypeId, Long pageNum, Long pageSize, String sortWay, boolean feeShipping) {
        List<GoodsSystemVo> goodsList = null;
//        如果不是热门推荐商品，则直接获取商品列表
        if (!tanpuhuiUtils.getGoodsTypeLabel(goodsTypeId).equals("热门推荐")) {
             goodsList = tanpuhuiUtils.selectTypeGoodsList(goodsTypeId, pageNum, pageSize, sortWay, feeShipping);
        }
//        如果是热门推荐商品，则获取所有相关商品类型列表，并获取所有相关商品列表
        else {
            // 获取所有相关商品类型Id列表
            List<Long> relevantTypeIdList = tanpuhuiUtils.getAllRelevantTypeIds(goodsTypeId);
            goodsList = tanpuhuiUtils.selectAllTypeGoodsList(relevantTypeIdList, pageNum, pageSize, sortWay, feeShipping);
        }
        return goodsList;
    }

    /**
     * 获取用户积分可折算的金额
     * @param userId
     * @return 可折算的金额
     */
    @Override
    public Double getUserDiscountRMB(Long userId){
        Long userCo2Reduce = userInfoService.getUserCo2Reduce(userId);
        String co2ReduceToRMB = sysConfigService.selectConfigByKey("co2Reduce_to_RMB");
        Double userDiscountRMB = userCo2Reduce * Double.parseDouble(co2ReduceToRMB);
        return userDiscountRMB;
    }

    @Override
    public List<GoodsVo> selectHotGoodsList(Long goodsTypeId, Long pageNum, Long pageSize, String sortWay, boolean feeShipping){
        Long offset = (pageNum - 1) * pageSize;
        return exchangeMallMapper.selectHotGoodsList(goodsTypeId, offset, pageSize, sortWay, feeShipping);
    }

    @Override
    public List<GoodsVo> selectTimeGoodsList(Long goodsTypeId,  Long pageNum,  Long pageSize, String sortWay, boolean feeShipping){
        Long offset = (pageNum - 1) * pageSize;
        return exchangeMallMapper.selectTimeGoodsList(goodsTypeId, offset, pageSize, sortWay, feeShipping);
    }

    @Override
    public List<GoodsEvaluateVo> selectGoodsEvaluateListByGoodsId(Long goodsId, Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return goodsEvaluateVoMapper.selectGoodsEvaluateListByGoodsId(goodsId, pageSize, offset);
    }

    @Override
    public List<Map<String,Object>> selectGoodsTypeList(Long goodsTypeId){
        String TypeRemark = sysDictDataService.selectRemark("goods_type", String.valueOf(goodsTypeId));
        return exchangeMallMapper.selectGoodsTypeList(TypeRemark);
    }

    @Override
    public void addCart(Long goodsId, Long userId, Long goodsCounts, String stander){
        exchangeMallMapper.addCart(goodsId, userId, goodsCounts, stander);
    }

    @Override
    public boolean isCartExists(Long userId, Long goodsId){
        return exchangeMallMapper.isCartExists(userId, goodsId);
    }

    @Override
    public void updateCart(Long goodsId, Long userId) {
        exchangeMallMapper.updateCart(goodsId, userId);
    }

    @Override
    public List<CartGoodsDTO> selectUserCartList(Long userId){
        List<CartGoodsDTO> cartGoodsDTOList = cartGoodsDTOMapper.selectUserCartList(userId);
        for (CartGoodsDTO cartGoodsDTO : cartGoodsDTOList) {
//            System.out.println(cartGoodsDTO);
            Cart cart = cartService.selectCartByCartId(cartGoodsDTO.getCartId());
            String standerSon = cart.getStander();
            System.out.println(standerSon);
            int standerIndex = tanpuhuiUtils.getStanderIndex(standerSon, cartGoodsDTO.getGoodsId());
            System.out.println(standerIndex);
            String[] goodsPriceList = cartGoodsDTO.getGoodsPrice().split("/");
            String[] goodsDiscountList = cartGoodsDTO.getGoodsDiscount().split("/");
            cartGoodsDTO.setGoodsPrice(goodsPriceList[standerIndex]);
            cartGoodsDTO.setStander(standerSon);
            cartGoodsDTO.setGoodsDiscount(goodsDiscountList[standerIndex]);
        }
//        System.out.println(cartGoodsDTOList);
        return cartGoodsDTOList;
    }

    @Override
    public void deleteCart(Long goodsId, Long userId){
        exchangeMallMapper.deleteCart(goodsId, userId);
    }

    @Override
    public  void reduceCartCounts(Long goodsId, Long userId){
        exchangeMallMapper.reduceCartCounts(goodsId, userId);
    }

    @Override
    public List<GoodsVo> selectGoodsByName(String goodsName, Long pageNum, Long pageSize, String sortWay, boolean feeShipping){
        Long offset = (pageNum - 1) * pageSize;
        return exchangeMallMapper.selectGoodsByName(goodsName, offset, pageSize, sortWay, feeShipping);
    }

    @Override
    public GoodsVo selectGoodsByStander(Long goodsId, String stander) {
        GoodsVo goodsVo = exchangeMallMapper.selectGoodsVoByGoodsId(goodsId);
        int StanderIndex = tanpuhuiUtils.getStanderIndex(stander, goodsId);
//        System.out.println(StanderIndex);
        String[] goodsPriceList = goodsVo.getGoodsPrice().split("/");
        String[] StanderList = goodsVo.getStander().split("/");
        String[] goodsDiscountList = goodsVo.getGoodsDiscount().split("/");
        goodsVo.setGoodsPrice(goodsPriceList[StanderIndex]);
        goodsVo.setStander(StanderList[StanderIndex]);
        goodsVo.setGoodsDiscount(goodsDiscountList[StanderIndex]);
        return goodsVo;
    }

    @Override
    public Long createOrderInfo(Long userId){
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        exchangeMallMapper.createOrderInfo(orderInfo);
        return orderInfo.getOrderId();
    }

    @Override
    public void createOrderItem(Long orderId, CartGoodsDTO cartGoodsDTO){
        exchangeMallMapper.createOrderItem(orderId, cartGoodsDTO);
    }

    @Override
    public List<GoodsVo> selectRelateGoodsList(String relateGoodsId){
        String[] relateGoodsIdList = relateGoodsId.split("/");
        List<GoodsVo> goodsVoList = new ArrayList<>();
        for (String goodsId : relateGoodsIdList) {
            GoodsVo goodsVo = exchangeMallMapper.selectGoodsVoByGoodsId(Long.parseLong(goodsId));
            goodsVoList.add(goodsVo);
        }
        return goodsVoList;
    }

    @Override
    public void createOrderItemRelate(Long orderId, String relateGoodsId){
        exchangeMallMapper.createOrderItemRelate(orderId, relateGoodsId);
    }

    @Override
    public List<Map<String, Object>> selectOrderShop(Long orderId){
        return exchangeMallMapper.selectOrderShop(orderId);
    }

    @Override
    public Map<String, Object> selectOrderListByOrderId(Long orderId){
        Map<String, Object> orderList = new HashMap<>();
        List<OrderItem> orderItemList = exchangeMallMapper.selectOrderItemByOrderId(orderId);
        System.out.println(orderItemList);
        for (OrderItem orderItem : orderItemList) {
            if (!orderList.keySet().contains(orderItem.getShopName())){
                orderList.put(orderItem.getShopName(), new ArrayList<>());
            }
            List<OrderItem> goodsList = (List<OrderItem>) orderList.get(orderItem.getShopName());
            goodsList.add(orderItem);
        }
        return orderList;
    }

    @Override
    public void payOrder(Map<String, Object> req){
        String payWay = req.get("payWay").toString();
        Map<String, Object> orderList = (Map<String, Object>) req.get("orderList");
        Map<String, Object> defaultAddress = (Map<String, Object>) req.get("defaultAddress");
        Long orderId = Long.parseLong(req.get("orderId").toString());
        System.out.println(req.get("orderPrice"));
        Double orderPrice = Double.parseDouble(req.get("orderPrice").toString());
//        System.out.println(defaultAddress);
//        System.out.println(orderId);
        String shippingMethods = (String) req.get("shippingMethods");
//        System.out.println(orderList.keySet());
        Double orderDeductPoint = 0.0;
        Double orderDeductAmount = 0.0;
        Long userId = Long.parseLong(req.get("userId").toString());
        for (String key : orderList.keySet()) {
            for (Map<String, Object> orderItem : (List<Map<String, Object>>)  orderList.get(key)){
                System.out.println(orderItem);
                orderDeductPoint += Double.valueOf(orderItem.get("usePoints").toString());
                exchangeMallMapper.payOrderUpdateOrderItem(Long.parseLong(orderItem.get("orderItemId").toString()), Double.valueOf(orderItem.get("usePoints").toString()), Double.valueOf(orderItem.get("transFee").toString()), orderItem.get("arrivalTime").toString(), shippingMethods);
                exchangeMallMapper.updateUserPoint(userId, Double.valueOf(orderItem.get("usePoints").toString()));
                exchangeMallMapper.updateGoodsInventory(Long.parseLong(orderItem.get("goodsId").toString()), Long.parseLong(orderItem.get("goodsCounts").toString()));
            }
        }
        exchangeMallMapper.payOrderUpdateOrderInfo(orderId, orderPrice, defaultAddress, payWay, orderDeductPoint);
    }

    @Override
    public void createOrderItemNow(Long orderId, Long goodsId, Long goodsCounts, String stander){
        int StanderIndex = tanpuhuiUtils.getStanderIndex(stander, goodsId);
        Goods good = goodsService.selectGoodsByGoodsId(goodsId);
        String[] goodsPriceList = good.getGoodsPrice().split("/");
        String[] goodsDiscountList = good.getGoodsDiscount().split("/");
        exchangeMallMapper.createOrderItemNow(orderId, goodsId, goodsCounts, goodsPriceList[StanderIndex], goodsDiscountList[StanderIndex], stander);
        if (good.getRelateGoodsId() != null){
            String[] relateGoodsIdList = good.getRelateGoodsId().split("/");
            if (relateGoodsIdList.length > 0){
                for (String relateGoodsId : relateGoodsIdList) {
                    exchangeMallMapper.createOrderItemRelate(orderId, relateGoodsId);
                }
            }
        }
    }
}
